﻿using System;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Threading;
using System.Windows.Forms;
using static AlarmManager;

namespace 定时提醒
{
    public partial class Form1 : Form
    {
        private SoundPlayer player;
        private AlarmManager alarmManager;

        // 声明控件
        private NotifyIcon notifyIcon;

        public Form1()
        {
            InitializeComponent();
            InitializeTrayIcon();

            alarmManager = new AlarmManager();
            alarmManager.LoadAlarmsFromIni();
            UpdateAlarmList();
        }

        //500ms周期定时器
        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateCurrentTime();//更新时间
            CheckAlarms();//检查是否有闹钟
        }

        //更新实时显示时间
        private void UpdateCurrentTime()
        {
            DateTime now = DateTime.Now;
            lblCurrentTime.Text = now.ToString("HH:mm:ss");
            lblCurrentDate.Text = now.ToString("yyyy-MM-dd dddd");
        }

       
        //添加闹钟
        private void button1_Click(object sender, EventArgs e)
        {
            DateTime TimeS=dtpAlarmTime.Value;
            foreach (var alarm in alarmManager.Alarms)
            {
                // 只比较小时和分钟
                if (alarm.Time.Hour == TimeS.Hour &&
                    alarm.Time.Minute == TimeS.Minute)
                {
                    MessageBox.Show($"{TimeS:HH:mm} 重复添加闹钟！", "提示",
                                  MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            // 添加新闹钟
            var newAlarm = new AlarmItem
            {
                Time = TimeS,
                Message = string.IsNullOrWhiteSpace(txtAlarmMessage.Text) ? "闹钟提醒" : txtAlarmMessage.Text,
                IsRepeat = chkRepeat.Checked,
                IsPrompt = chkPrompt.Checked,
                PromptSound = chkPromptSound.Checked,
                IsEnabled = true
            };

            alarmManager.AddAlarm(newAlarm);
            alarmManager.List_Sorting();
            UpdateAlarmList();
            //SaveAlarmsToFile();

            // 清空输入框
            txtAlarmMessage.Text = "闹钟提醒";
            chkRepeat.Checked = false;

            MessageBox.Show("闹钟添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        //更新显示列表
        private void UpdateAlarmList()
        {
            listBoxAlarms.Items.Clear();

            foreach (var alarm in alarmManager.Alarms)
            {
                string status = "1状态:" +(alarm.IsEnabled ? "启用" : "禁用");
                string repeat = "2模式:" + (alarm.IsRepeat ? "重复" : "一次性");
                string Prompt = "3弹出提示:" + (alarm.IsPrompt ? "启用" : "禁用");
                string PromptSound = "4提示音:" + (alarm.PromptSound ? "启用" : "禁用");
                string displayText = $"{alarm.Time:HH:mm} - {alarm.Message} ({status}，{repeat}，{Prompt}，{PromptSound})";
                listBoxAlarms.Items.Add(displayText);
            }
        }

        //检查闹钟
        private void CheckAlarms()
        {
            DateTime now = DateTime.Now;

            foreach (var alarm in alarmManager.Alarms.ToList())
            {
                if (alarm.IsEnabled && alarm.Time.Hour == now.Hour && alarm.Time.Minute == now.Minute)
                {
                    // 检查是否已经触发过（避免重复触发）
                    if (!alarm.LastTriggered.HasValue ||
                        alarm.LastTriggered.Value.Date != now.Date ||
                        alarm.LastTriggered.Value.Hour != now.Hour ||
                        alarm.LastTriggered.Value.Minute != now.Minute)
                    {
                        // 立即触发闹钟，不等待
                        if (alarm.PromptSound) 
                        {
                            //PlayAudio();
                            PlayAudioTimes(3);
                        }
                        alarm.LastTriggered = now;

                        // 调试信息（可选）
                        //Console.WriteLine($"闹钟触发: {alarm.Time:HH:mm} - {alarm.Message} at {now:HH:mm:ss.fff}");
                    }
                }
            }
        }

        //删除按钮
        private void button3_Click(object sender, EventArgs e)
        {
            // 删除选中的闹钟
            if (listBoxAlarms.SelectedIndex >= 0)
            {
                AlarmItem alarmItem = alarmManager.Alarms[listBoxAlarms.SelectedIndex];

                var result = MessageBox.Show($"确定要删除 {alarmItem.Time:HH:mm} 这个闹钟吗？",
                    "确认删除",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    alarmManager.RemoveAlarm(listBoxAlarms.SelectedIndex);
                    alarmManager.List_Sorting();
                    UpdateAlarmList();
                }
            }
            else
            {
                MessageBox.Show("请先选择一个闹钟进行删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 记录当前播放次数
        private int _playCount = 0;

        // 播放音频指定次数
        private void PlayAudioTimes(int times)
        {
            if (times <= 0) return;

            _playCount = times;
            PlayAudioWithCount();
        }

        // 带计数器的播放方法
        private void PlayAudioWithCount()
        {
            if (_playCount <= 0) return;

            try
            {
                // 初始化播放器并指定音频路径
                player = new SoundPlayer(@"Audio.wav");

                // 使用新线程播放，避免阻塞UI
                Thread thread = new Thread(() =>
                {
                    player.PlaySync(); // 同步播放，完成后才会继续
                    _playCount--;      // 减少播放次数

                    // 如果还需要继续播放，递归调用
                    if (_playCount > 0)
                    {
                        // 使用Invoke确保在UI线程上调用（如果需要更新UI）
                        this.Invoke((MethodInvoker)delegate {
                            PlayAudioWithCount();
                        });
                    }
                });
                thread.IsBackground = true;
                thread.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("播放失败: " + ex.Message);
            }
        }

        //窗口关闭时
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 显示确认对话框
            DialogResult result = MessageBox.Show(
                "确定要关闭窗口吗？",
                "关闭确认",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            // 如果用户选择"否"，则取消关闭操作
            if (result == DialogResult.No)
            {
                e.Cancel = true;  // 阻止窗体关闭
            }
        }

        //初始化托盘
        private void InitializeTrayIcon()
        {
            // 创建托盘图标   
            notifyIcon = new NotifyIcon
            {
                Icon = new Icon("app_icon.ico"), // 使用应用程序图标
                Text = "定时提醒",
                Visible = false // 初始不显示
            };

            // 双击托盘图标恢复窗口
            notifyIcon.DoubleClick += (s, e) => ShowMainWindow();

            // 创建右键菜单
            var contextMenu = new ContextMenuStrip();
            contextMenu.Items.Add("显示主窗口", null, (s, e) => ShowMainWindow());
            contextMenu.Items.Add("退出", null, (s, e) => ExitApplication());

            notifyIcon.ContextMenuStrip = contextMenu;
        }

        //托盘事件显示主程序
        private void ShowMainWindow()
        {
            Show();
            WindowState = FormWindowState.Normal;
            notifyIcon.Visible = false;
        }

        //托盘事件退出
        private void ExitApplication()
        {
            notifyIcon.Visible = false; // 必须清理托盘图标
            Application.Exit();
        }

        //后台运行小图标
        private void button4_Click(object sender, EventArgs e)
        {
            Hide(); // 隐藏主窗口
            notifyIcon.Visible = true; // 显示托盘图标
        }

        //编辑闹钟
        private void button2_Click(object sender, EventArgs e)
        {
            // 编辑选中的闹钟
            if (listBoxAlarms.SelectedIndex >= 0)
            {
                var selectedAlarm = alarmManager.Alarms[listBoxAlarms.SelectedIndex];

                // 创建Form2实例
                Form2 form2 = new Form2();

                // 将选中的闹钟信息传递给Form2
                form2.SetAlarmInfo(selectedAlarm, listBoxAlarms.SelectedIndex);

                // 显示Form2作为模态对话框
                // 这样Form1会被禁用，直到Form2关闭
                DialogResult result = form2.ShowDialog(this);

                // 如果Form2返回OK，则更新闹钟的Message
                if (result == DialogResult.OK)
                {
                    int      alarmIndex  = form2.GetAlarmIndex();
                    DateTime Time        = form2.GetAlarmTime();
                    string   newMessage  = form2.GetAlarmMessage();
                    bool     IsRepeat    = form2.GetAlarmRepeat();
                    bool     IsPrompt    = form2.GetAlarmPrompt();
                    bool     PromptSound = form2.GetAlarmPromptSound();
                    bool     IsEnabled   = form2.GetAlarmEnabled();

                    if (alarmIndex >= 0 && alarmIndex < alarmManager.Alarms.Count)
                    {
                        alarmManager.Alarms[alarmIndex].Time        = Time;
                        alarmManager.Alarms[alarmIndex].Message     = newMessage;
                        alarmManager.Alarms[alarmIndex].IsRepeat    = IsRepeat;
                        alarmManager.Alarms[alarmIndex].IsPrompt    = IsPrompt;
                        alarmManager.Alarms[alarmIndex].PromptSound = PromptSound;
                        alarmManager.Alarms[alarmIndex].IsEnabled   = IsEnabled;

                        MessageBox.Show("修改成功","提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 刷新ComboBox显示
                        UpdateAlarmList();
                        listBoxAlarms.SelectedIndex = alarmIndex;
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择一个闹钟进行编辑", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //保存按钮
        private void button5_Click(object sender, EventArgs e)
        {
            alarmManager.SaveAlarmsToIni();
            MessageBox.Show("闹钟已保存到文件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
